import cv2
import numpy as np
from utils.common import load_image, show_image, make_dirs  # 导入公共函数
from utils.config import exp3_contours_path, exp3_output_dir  # 导入输出路径


# 确保输出目录存在
make_dirs(exp3_output_dir)

# 加载图片并显示
image = load_image()

# 将图像转换为灰度图
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 对灰度图进行二值化处理
_, binary_image = cv2.threshold(gray_image, 128, 255, cv2.THRESH_BINARY)

# 轮廓提取
contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

#创建彩色图像用于绘制轮廓
contours_image = cv2.cvtColor(gray_image, cv2.COLOR_GRAY2BGR)
# 遍历轮廓并计算特征
for contour in contours:
    area = cv2.contourArea(contour)
    perimeter = cv2.arcLength(contour, True)
    print(f"Contour Area: {area}, Perimeter: {perimeter}")

# 绘制轮廓
cv2.drawContours(contours_image, contours, -1, (0, 255, 0), 2)
# cv2.drawContours(image, [contour], -1, (0, 255, 0), 2)

show_image("Contour Image",contours_image)
# 保存结果
cv2.imwrite(exp3_contours_path, contours_image)
print(f"轮廓绘制已保存到：{exp3_contours_path}")